import { message } from 'antd';
import { isExternal } from '../_utils/url';
import { AppContext } from '../AppProvider';
import React, { useContext, useState } from 'react';

const useFileDownload = ({ apiPrefix, newWindow, params, method, downloadName, url, data }: any) => {
  const [loading, setLoading] = useState(false)

  const { request, commonHeaders, apiPrefix: apiPrefixContext='' } = useContext(AppContext)
  const onClick = async () => {
    try {
      setLoading(true)
      let _data = data instanceof Function ? data() : data;
      let _params = params instanceof Function ? params() : params;
      if (!isExternal(url)) {

        url = apiPrefix ? `${apiPrefix}${url}` : `${apiPrefixContext}${url}`
      }

      if (newWindow) {
        window.open(url)
        return
      }
      let req;
      // if (request) {
      //   req = request();
      // } else {
      req = request({
        url,
        responseType: "blob",
        header: {
          "response-type": "stream",
          ...commonHeaders,
          // ...headers,
        },
        data: _data,
        params: _params,
        noDealError: true,
        noDealData: true,
        downloadFile: true,
        method,
      });
      // }
      req.then((res: any) => {
        let a = document.createElement("a");
        a.download = downloadName || basename(url);
        a.href = window.URL.createObjectURL(res);
        a.click();
      }).catch(error=>{
        console.log("DownloadFile", error);
        message.error('下载错误，请右键保存')
        setTimeout(()=>{

          window.open(url)
        },1000)
      });
    } catch (error) {
      console.log("DownloadFile", error);
      console.log("DownloadFile", error);
      message.error('下载错误，请右键保存')
      setTimeout(()=>{

        window.open(url)
      },1000)
    } finally {
      setLoading(false);

    }
  }
  return {
    onClick,
    loading
  }
}
function basename(str: string) {
  //   @ts-ignore
  return str.split("/").pop().split("?")[0];
}
export default useFileDownload